package com.stox.client.ui.javafx.chartingy.event.listener;

import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;

import com.stox.client.ui.javafx.chartingy.view.ChartingView;
import com.stox.shared.model.intf.Callback;

public class PanMouseEventStrategy implements ChartingMouseEventStrategy {

	private ChartingView chartingView;
	private double startX;

	@Override
	public void handle(final MouseEvent event) {
		if (!event.isConsumed() && MouseButton.PRIMARY.equals(event.getButton())) {
			if (MouseEvent.MOUSE_PRESSED.equals(event.getEventType())) {
				startX = event.getX();
			} else if (MouseEvent.MOUSE_DRAGGED.equals(event.getEventType())) {
				final double x = event.getX();
				final double width = chartingView.getPrimaryChart().getChartContentArea().getWidth();
				final double max = chartingView.getRangeSlider().getMax();
				final double min = chartingView.getRangeSlider().getMin();
				final double low = chartingView.getRangeSlider().getLowValue();
				final double high = chartingView.getRangeSlider().getHighValue();
				final double delta = ((x - startX) * (high - low)) / width;
				if (((low - delta) >= min) && ((high - delta) <= max)) {
					chartingView.getRangeSlider().setLowValue(low - delta);
					chartingView.getRangeSlider().setHighValue(high - delta);
					startX = x;
				}
			}
		}
	}

	@Override
	public void attach(final ChartingView chartingView) {
		if (null != this.chartingView) {
			throw new IllegalArgumentException();
		}
		this.chartingView = chartingView;
		chartingView.getSplitPane().addEventFilter(MouseEvent.MOUSE_PRESSED, this);
		chartingView.getSplitPane().addEventFilter(MouseEvent.MOUSE_DRAGGED, this);
	}

	@Override
	public void detach(final ChartingView chartingView) {
		chartingView.getSplitPane().removeEventFilter(MouseEvent.MOUSE_PRESSED, this);
		chartingView.getSplitPane().removeEventFilter(MouseEvent.MOUSE_DRAGGED, this);
		this.chartingView = null;
	}

	@Override
	public void setCompletionCallback(final Callback<Void, Void> completionCallbak) {

	}

}
